package com.itchu.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itchu.common.domain.PageResult;
import com.itchu.common.exption.ExceptionEnum;
import com.itchu.common.exption.MusicException;
import com.itchu.system.domain.Singer;
import com.itchu.system.domain.Song;
import com.itchu.system.mapper.SingerMapper;
import com.itchu.system.mapper.SongMapper;
import com.itchu.system.service.CheckService;
import com.itchu.system.service.SongService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CheckServiceImpl implements CheckService {

    @Autowired
    private SongMapper songMapper;
    @Autowired
    private SingerMapper singerMapper;

    /**
     * 查找歌曲的分页信息
     * @param key   搜索条件
     * @param page  当前页
     * @param rows  页大小
     * @return
     */
    @Override
    public PageResult<Song> showAll(String key, Integer page, Integer rows,Integer state) {
        //开启分页
        PageHelper.startPage(page,rows);
        //创建一个封装条件的对象
        Example example = new Example(Song.class);
        //判断搜索条件是否有值
        if (!StringUtils.isEmpty(key)) {
            Example.Criteria criteria = example.createCriteria();
            criteria.orLike("name","%"+key+"%");
        }

        // 只显示审核的歌曲
        if (state.equals(0)) {
            // 显示待审核和审核不通过的歌曲
            example.createCriteria().andNotEqualTo("state",state);
        }else {
            example.createCriteria().andEqualTo("state",state);
        }

        List<Song> list = songMapper.selectByExample(example);
        List<Singer> singers = singerMapper.selectAll();
        list.stream().forEach(song -> {
            singers.stream().forEach(singer -> {
                if (song.getSingerId().equals(singer.getId())) {
                    song.setSinger(singer);
                }
            });
        });
        PageInfo<Song> pageInfo = new PageInfo<>(list);
        return new PageResult<>(pageInfo.getTotal(),pageInfo.getPages(),list);
    }

    /**
     * 审核的操作，0代表通过，2代表不通过
     * @param songId
     * @param state
     * @return
     */
    @Override
    public void changeState(Long songId, Integer state) {
        Song song = new Song();
        song.setId(songId);
        song.setState(state);
        songMapper.updateByPrimaryKeySelective(song);
    }
}
